package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ApReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult readCount(ApReadBehaviorDto dto) {
        //1.校验参数
        if(dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户id
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.将数据存储到redis中
        String obj = (String)cacheService.hGet("read_" + dto.getArticleId(), AppThreadLocalUtil.getUser().getId().toString());
        //判断该用户是否读过该文章
        if(obj != null){
            //读过该文章
            ApReadBehaviorDto apReadBehaviorDto = JSON.parseObject(obj,ApReadBehaviorDto.class);
            dto.setCount(apReadBehaviorDto.getCount()+dto.getCount());
        }
        //将数据缓存到redis中
        cacheService.hPut("read_" + dto.getArticleId(), AppThreadLocalUtil.getUser().getId().toString(),JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
